package com.chinatechstar.decis.service.impl;

import java.util.*;

import com.chinatechstar.admin.entity.SysUser;
import com.chinatechstar.admin.mapper.SysUserMapper;
import com.chinatechstar.component.commons.exception.AjaxExceptionEnum;
import com.chinatechstar.component.commons.utils.CurrentUserUtils;
import com.chinatechstar.component.commons.utils.DateUtils;
import com.chinatechstar.decis.entity.DecisEconOil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chinatechstar.decis.entity.DecisEconWater;
import com.chinatechstar.decis.mapper.DecisEconWaterMapper;
import com.chinatechstar.decis.service.DecisEconWaterService;
import com.chinatechstar.component.commons.result.PaginationBuilder;
import com.chinatechstar.component.commons.utils.SequenceGenerator;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

/**
 * 业务逻辑实现层
 *
 * @author Rei
 */
@Service
@Transactional
public class DecisEconWaterServiceImpl implements DecisEconWaterService {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    private static final SequenceGenerator SEQUENCE_GENERATOR = new SequenceGenerator();

    @Autowired
    private DecisEconWaterMapper decisEconWaterMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询所有数据
     */
    @Override
    public List<DecisEconWater> findDecisEconWaterAll() {
        return decisEconWaterMapper.findDecisEconWaterAll();
    }

    /**
     * 查询分页
     */
    @Override
    public Map<String, Object> findDecisEconWaterByCondition(Integer currentPage, Integer pageSize, String name, String sorter) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        if (StringUtils.isNotBlank(sorter)) {
            String sort = sorter.substring(0, sorter.lastIndexOf('_'));
            String sequence = "ascend".equals(sorter.substring(sorter.lastIndexOf('_') + 1)) ? "ASC" : "DESC";
            paramMap.put("sort", sort);
            paramMap.put("sequence", sequence);
        } else {
            paramMap.put("sort", "createTime");
            paramMap.put("sequence", "DESC");
        }
        Page<Object> page = PageHelper.startPage(currentPage, pageSize);
        List<LinkedHashMap<String, Object>> resultList = decisEconWaterMapper.findDecisEconWaterByCondition(paramMap);
        return PaginationBuilder.buildResult(resultList, page.getTotal(), currentPage, pageSize);
    }

    /**
     * 查询导出数据列表
     */
    @Override
    public List<LinkedHashMap<String, Object>> findDecisEconWaterForExcel(Map<String, Object> paramMap) {
        return decisEconWaterMapper.findDecisEconWaterByCondition(paramMap);
    }

    /**
     * 根据主键ID数据查询数据
     */
    @Override
    public DecisEconWater findDecisEconWaterById(Long id) {
        return decisEconWaterMapper.findDecisEconWaterById(id);
    }

    /**
     * 根据主键ID数组查询数据
     */
    @Override
    public List<DecisEconWater> findDecisEconWaterByIds(Long[] ids) {
        return decisEconWaterMapper.findDecisEconWaterByIds(ids);
    }

    /**
     * 新增或编辑
     */
    @Override
    public void editDecisEconWater(DecisEconWater decisEconWater) {
        Date yearDate = decisEconWater.getDecisewaterYear();
        Integer month = decisEconWater.getDecisewaterMonth();
        if (yearDate == null || month == null) {
            throw new IllegalArgumentException(AjaxExceptionEnum.DATE_IS_NULL.getMsg());
        }

        Long econWaterId = decisEconWater.getId();
        DecisEconWater temp;


        // 根据id判断是否存在，存在需要查询一次，防止修改日期
        if (econWaterId == null) {
            int year = DateUtils.getYear(yearDate);
            temp = decisEconWaterMapper.findDecisEconWaterByYearMon(year, month);
            if (temp != null) {
                throw new IllegalArgumentException(AjaxExceptionEnum.ECON_WATER_ALREADY_EXISTS.getMsg());
            }

            SysUser currUser = sysUserMapper.getUserByUsername(CurrentUserUtils.getOAuth2AuthenticationInfo().get("name"));

            decisEconWater.setId(SEQUENCE_GENERATOR.nextId());
            decisEconWater.setCreateName(currUser.getNickname());
            decisEconWater.setCreateUsername(currUser.getUsername());
            decisEconWaterMapper.insertDecisEconWater(decisEconWater);
            logger.info("已新增： {}", econWaterId);
        } else {
            temp = decisEconWaterMapper.findDecisEconWaterById(econWaterId);
            if (temp == null) {
                throw new IllegalArgumentException(AjaxExceptionEnum.ECON_WATER_NOT_FIND.getMsg());
            }
            decisEconWater.setDecisewaterPrice(temp.getDecisewaterPrice());
            decisEconWaterMapper.updateDecisEconWater(decisEconWater);
            logger.info("已编辑： {}", econWaterId);
        }
    }

    /**
     * 批量新增
     */
    @Override
    public void insertDecisEconWaters(List<DecisEconWater> decisEconWaters) {
        SysUser currUser = sysUserMapper.getUserByUsername(CurrentUserUtils.getOAuth2AuthenticationInfo().get("name"));

        for (DecisEconWater decisEconWater : decisEconWaters) {
            decisEconWater.setId(SEQUENCE_GENERATOR.nextId());
            decisEconWater.setCreateName(currUser.getNickname());
            decisEconWater.setCreateUsername(currUser.getUsername());
        }
        decisEconWaterMapper.insertDecisEconWaters(decisEconWaters);
    }

    /**
     * 编辑
     */
    @Override
    public void updateDecisEconWater(DecisEconWater decisEconWater) {
        decisEconWaterMapper.updateDecisEconWater(decisEconWater);
        logger.info("已编辑： {}", decisEconWater.getId());
    }

    /**
     * 批量编辑
     */
    @Override
    public void updateDecisEconWaters(List<DecisEconWater> decisEconWaters) {
        decisEconWaterMapper.updateDecisEconWaters(decisEconWaters);
    }

    /**
     * 删除
     */
    @Override
    public void deleteDecisEconWaterById(Long id) {
        decisEconWaterMapper.deleteDecisEconWaterById(id);
    }

    /**
     * 批量删除
     */
    @Override
    public void deleteDecisEconWaterByIds(Long[] ids) {
        decisEconWaterMapper.deleteDecisEconWaterByIds(ids);
    }

}